import Vue from 'vue'
import axios from 'axios'
// 创建各接口请求方法的实例
const service = axios.create({
  baseURL: '', //api的base_url
  timeout: 30000 //请求超时时间设置
});
// 请求异常信息统一处理
const error = (err) => {
  console.log(err)
  if (err.response) {
    console.log(err)
    if (err.response.status === 403) {
      // 举例针对403的一些异常处理
    }
  }
  return Promise.reject(err)
};

// 对请求（request）拦截处理
var reg = new RegExp('rest')

const requestBefore=(config)=>{
  // $.ajax("../rest/refreshToken/?refreshToken=" + localStorage.getItem('refreshToken') + '&username=' + localStorage.getItem('principal'), {
  //     method: "get",
  //     contentType: "application/json;charset=utf-8",
  //     success: res => {
  //       localStorage.setItem('credentials',res.data.credentials)
  //       localStorage.setItem('principal',res.data.principal)
  //       localStorage.setItem('refreshToken',res.data.refreshToken)
  //     }
  // });
  if(!config.url.match(reg)){
    const token = sessionStorage.getItem('credentials')
    const useragentcode = sessionStorage.getItem('useragentcode')
    if (token) {
      config.headers['Authorization'] = token
      config.headers['useragentcode'] = useragentcode
    }
  }
  return config;
}
service.interceptors.request.use(requestBefore,error);

// 对响应（response）进行统一处理
service.interceptors.response.use((response) => {
  // console.log('response',response)
  let code = response.code;
  switch (code) {
    case '401':      
    break
  }
  return response.data
},error);


export function download(obj = {}) {
  obj.headers = {
    "Content-Type": "application/json"
  }
  obj.responseType = "blob"


  if (obj.method == 'post') obj.data = params
  else obj.params = obj.params
  return service(obj)
    .then(data => {
      // console.log('data', data);
      if (!data || data.size === 0 || data.type === 'application/json') {
        data.text().then(res => {
          let result;
          res && (result = JSON.parse(res));
          Message.info(
            result && result.msg ? result.msg : '查询数据为空，导出失败！'
          )
        })
        return;
      }

      const content = data;
      const blob = new Blob([content]);
      if ("download" in document.createElement("a")) {
        const elink = document.createElement("a");
        elink.download = obj.name;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      } else {
        navigator.msSaveBlob(blob, obj.name);
      }
    })
    .catch(r => {
      console.error(r);
    }).finally(() => obj.callback && obj.callback());
}

export default service

